﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Yichat.MicroService.Model
{
    public static class CacheItemExtensions
    {
        public static IDistributeionCacheEntry<TValue> ToCacheEntry<TValue>(this CacheItem cacheItem)
        {
            var item = JsonConvert.DeserializeObject<TValue>(cacheItem.Value);
            DateTimeOffset? dt = null;
            if (cacheItem.AbsoluteExpiration.HasValue)
            {
                dt = DateTime.SpecifyKind(cacheItem.AbsoluteExpiration.Value, DateTimeKind.Utc);
            }
            TimeSpan? ms = null;
            if (cacheItem.SlidingExpiration.HasValue)
            {
                ms = TimeSpan.FromMilliseconds(cacheItem.SlidingExpiration.Value);
            }

            var cacheEntry = new DistributeionCacheEntry<TValue>(cacheItem.Key, item, ms, dt);
            cacheEntry.LastAccessUtc = cacheItem.LastAccessUtc;
            cacheEntry.CreatedUtc = cacheItem.CreatedUtc;
            cacheEntry.CacheExpireStategy = (CacheExpireStategy)cacheItem.CacheExpireStategy;
            return cacheEntry;
        }
    }
}
